package com.ywb.ex05;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

@SuppressWarnings("serial")
public class Task2 extends JFrame {

    private JTextArea ta_content;
    private JTextField tf_address;

    public static void main(String args[]) {
        EventQueue.invokeLater(() -> {
            try {
                Task2 frame = new Task2();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    public Task2() {
        super();
        setTitle("解析网页中的内容");
        setBounds(100, 100, 484, 375);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final JPanel panel = new JPanel();
        getContentPane().add(panel, BorderLayout.NORTH);

        final JLabel label = new JLabel();
        label.setText("输入网址：");
        panel.add(label);

        tf_address = new JTextField();
        tf_address.setPreferredSize(new Dimension(260, 25));
        panel.add(tf_address);

        final JButton button = new JButton();
        button.addActionListener(e ->  {
//            请清空文本框
            ta_content.setText("");
            String address = tf_address.getText().trim();// 获得输入的网址
            try {
                Collection urlCollection = getURLCollection(address);// 调用方法，获得网页内容的集合对象
                Iterator it = urlCollection.iterator(); // 获得集合的迭代器对象
                while (it.hasNext()) {
                    ta_content.append(it.next() + "\n"); // 在文本域中显示解析的内容
                }

            }catch (IOException ie){
                ie.printStackTrace();
            }
        });
        button.setText("解析网页");
        panel.add(button);

        final JScrollPane scrollPane = new JScrollPane();
        getContentPane().add(scrollPane, BorderLayout.CENTER);

        ta_content = new JTextArea();
        ta_content.setFont(new Font("", Font.BOLD, 14));
        scrollPane.setViewportView(ta_content);
        //
    }

    public Collection<String> getURLCollection(String urlString) throws IOException {
        // 声明URL
        URL url = new URL(urlString);
        // 创建集合对象
        Collection<String> urlCollection = new ArrayList<>();
//        将字节流以utf-8的形式转化为字符流
        BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream(),"utf-8"));
        String s;
        while((s = br.readLine()) != null){
            urlCollection.add(s);
        }
        return urlCollection;
    }
}
